<?php
header('Content-Type:text/html;charset=utf8');
//用户点击企业站
//insert_click_visit
include_once './db.php';
include_once './function.php';
$db = DB::getIntance();
$db_table = 'days_visits';

$cpid = (int)$_GET['cpid'];
$date = $_GET['date'];// 点击时的日期
$open_date = $_GET['open_date'];// 企业开户日期

if (!$cpid || !$date) {
    echo json_encode(array('code' => 0, 'msg' => '缺少参数', 'data' => '',));
    exit();
}

$sql = "select id,visit from " . $db_table . " where cpid = '" . $cpid . "' and `date` = '" . $date . "'";
$res = $db->getRow($sql);

if (empty($res)) {//企业当天没有点击记录则新增
    if ($open_date) {
        //判断开户日期到点击日期间隔
        $num = (strtotime($date) - strtotime($open_date)) / 86400;
        $last_date = date('Y-m-d', (strtotime($date) - 86400));
        if ($num < 30) {//小于30天取开户日期到点击日期
            $date_arr = getDateFromRange($open_date, $last_date);

        } else {//大于30天取近30天到点击日期
            $start_time = strtotime($date) - 86400 * 30;
            $date_arr = getDateFromRange(date('Y-m-d', $start_time), $last_date);
        }
    }

    if (empty($date_arr)) {
        echo json_encode(array('code' => 0, 'msg' => '日期错误', 'data' => '',));
        exit();
    }
    foreach ($date_arr as $value) {
        insert_visit($cpid, $value);
    }

    $db->insert($db_table, array(
        'cpid' => $cpid,
        'date' => $date,
        'created_at' => date('Y-m-d H:i:s', time()),
        'visit' => click_nums(1)
    ));
} else {//有点击记录则修改
    if ($res['visit'] < 20) {
        $visit = click_nums(1) + $res['visit'];
    } elseif ($res['visit'] > 20 && $res['visit'] < 150) {
        $visit = click_nums(2) + $res['visit'];
    } elseif ($res['visit'] > 150) {
        $visit = 1 + $res['visit'];
    }

    $db->update($db_table, array(
        'updated_at' => date('Y-m-d H:i:s', time()),
        'visit' => $visit
    ), array('id' => $res['id']));
}

echo json_encode(array('code' => 1, 'msg' => '添加成功', 'data' => ''));